﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Data.Base;

namespace XfTechOAWeb.EFCore.Base
{
    /// <summary>
    /// 工作单元管理类
    /// </summary>
    public class UnitOfWorkManage : IUnitOfWorkManage
    {
        private readonly DbContext _db;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db"></param>
        public UnitOfWorkManage(DbContext db)
        {
            _db = db;
        }

        private int _tranCount { get; set; }
        public int TranCount => _tranCount;

        /// <summary>
        /// 开启事务
        /// </summary>
        public void BeginTran()
        {
            lock (this)
            {
                _tranCount++;
                _db.Database.BeginTransaction();
            }
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void CommitTran()
        {
            lock (this)
            {
                _tranCount--;
                if (_tranCount == 0)
                {
                    try
                    {
                        _db.Database.CommitTransaction();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        _db.Database.RollbackTransaction();
                    }
                }
            }
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void RollbackTran()
        {
            lock (this)
            {
                _tranCount--;
                _db.Database.RollbackTransaction();
            }
        }
    }
}
